//
//  PersonalCenterVC.m
//  phmall
//
//  Created by admin on 2017/9/15.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "PersonalCenterVC.h"
#import "OrderListVC.h"
#import "ViewController.h"
//#import "MessageViewController.h"
#import "MyFavoriteVC.h"
//#import "ChatViewController.h"
#import "UserInfoModel.h"
#import "PersonalDataVC.h"
#import "FinancialDetailsVC.h"
#import "GetDiscountCouponVC.h"
#import "MyGetDiscountCouponVC.h"
#import "ShippingAddressVC.h"
#import "MyShareViewController.h"
#import "RefundViewController.h"
#import "IntegralStorePageVC.h"
#import "ShortMessageVC.h"
#import "CreditViewController.h"
#import "AocialContactVC.h"
#import <WebKit/WebKit.h>
@interface PersonalCenterVC ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>{
    UIView *headView;
    NSString *alpha;
    UILabel *name;
    UILabel *integral;
    UIImageView *head;
//    UIButton *login;

}
@property(strong,nonatomic)UserInfoModel *model;
@property(strong,nonatomic)UITableView *myTableview;
@end

@implementation PersonalCenterVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadDataWithInfo];
    self.navBarBgAlpha=@"0.0";
    self.navigationController.navigationBar.barTintColor =  [UIColor whiteColor];
}
- (void)loadDataWithInfo{

    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_index/get_member_info"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [self analysisDataWithMemberInfoDictionary:response[@"data"][0]];
        }else{
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
//            [PublicClass ProgressHUDModeText:@"账号未登录或登录已过期" andTime:2];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}
- (void)analysisDataWithMemberInfoDictionary:(NSDictionary*)dictionary{
    self.model = [UserInfoModel yy_modelWithDictionary:dictionary];
    [head sd_setImageWithURL: [NSURL URLWithString:[NSString stringWithFormat:@"%@union/images/%@",IMGURL,self.model.member_image]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
    integral.text=[NSString stringWithFormat:@"%@  :  %@",Localized(@"积分"),self.model.member_point];
    name.text=self.model.member_id;
    
    YYCache *cache = [YYCache cacheWithName:@"user"];
    [cache setObject:dictionary forKey:@"userInfo"];

    [self.myTableview reloadData];
}
-(void)butAction:(UIButton *)sender{
//    if (![[EMClient sharedClient] isAutoLogin]) {
//        [self whetherLogin];
//        return;
//    }
    switch (sender.tag-500) {
        case 0:
            [self getAddress];
            break;
        case 1:
            [self integral];
            break;
        case 2:
            [self favorite];
            break;
        case 3:
            [self shortMessage];
            break;
        case 4:
            [self getSiscountCoupon];
            break;
        case 5:
            [self getShare];
            break;
        case 6:
            [self credit];
            break;
        case 7:
            [self financialDetails];
            break;
        case 8:
            [self aocialContact];
            break;
        default:
            break;
    }
}
-(void)aocialContact{
    self.hidesBottomBarWhenPushed=YES;
    AocialContactVC *favorite=[[AocialContactVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)shortMessage{
    self.hidesBottomBarWhenPushed=YES;
    ShortMessageVC *favorite=[[ShortMessageVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)credit{
    self.hidesBottomBarWhenPushed=YES;
    CreditViewController *favorite=[[CreditViewController alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)refund{
    self.hidesBottomBarWhenPushed=YES;
    RefundViewController *favorite=[[RefundViewController alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)integral{
    self.hidesBottomBarWhenPushed=YES;
    IntegralStorePageVC *favorite=[[IntegralStorePageVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)favorite{
    self.hidesBottomBarWhenPushed=YES;
    MyFavoriteVC *favorite=[[MyFavoriteVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)financialDetails{
    self.hidesBottomBarWhenPushed=YES;
    FinancialDetailsVC *favorite=[[FinancialDetailsVC alloc]init];
    favorite.moneyStr=self.model.member_money;
    favorite.pointStr=self.model.member_point;
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)getSiscountCoupon{
    self.hidesBottomBarWhenPushed=YES;
    MyGetDiscountCouponVC *favorite=[[MyGetDiscountCouponVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)getAddress{
    self.hidesBottomBarWhenPushed=YES;
    ShippingAddressVC *favorite=[[ShippingAddressVC alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)getShare{
    self.hidesBottomBarWhenPushed=YES;
    MyShareViewController *favorite=[[MyShareViewController alloc]init];
    [self.navigationController pushViewController:favorite animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)rightBarAction{
    

}

-(void)leftBarAction{
    self.hidesBottomBarWhenPushed=YES;
    PersonalDataVC *chatController = [[PersonalDataVC alloc] init];
    chatController.model=self.model;
    [self.navigationController pushViewController:chatController animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
  

    UIBarButtonItem*  rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"消息-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarAction)];
    
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"设置"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(-(STATUS_BAR_HEIGHT+44));
        make.left.right.equalTo(self.view).priorityHigh();
        make.bottom.equalTo(self.view).with.offset(0).priorityHigh();
    }];
    
    headView=[UIView new];
    headView.backgroundColor=[UIColor whiteColor];
    
    UIImageView *logBack=[[UIImageView alloc]init];
    logBack.userInteractionEnabled=YES;
    [headView addSubview:logBack];
    [logBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView);
        make.left.right.equalTo(headView);
        make.height.offset(200+STATUS_BAR_HEIGHT);
    }];
    logBack.backgroundColor=[UIColor colorWithHexString:@"#fe9b0c"];


    head=[[UIImageView alloc]init];
    [logBack addSubview:head];
    [head sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"头像"]];
    ViewBorderRadius(head, 40, 0, [UIColor clearColor]);
    [head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logBack).offset(STATUS_BAR_HEIGHT+44);
        make.centerX.equalTo(logBack);
        make.width.height.offset(80);
    }];

    name=[[UILabel alloc]init];
    name.textColor=[UIColor whiteColor];
    [logBack addSubview:name];
    name.text=@"XXXXXX";
    name.font=[UIFont systemFontOfSize:15];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(logBack);
        make.top.equalTo(head.mas_bottom).offset(5);
    }];

    integral=[[UILabel alloc]init];
    integral.textColor=[UIColor whiteColor];
    [logBack addSubview:integral];
    integral.font=[UIFont systemFontOfSize:15];
    [integral mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(logBack);
        make.top.equalTo(name.mas_bottom).offset(5);
    }];
    integral.text=[NSString stringWithFormat:@"积分  :  9999"];
    
    
    UIView *order=[[UIView alloc] init];
    [headView addSubview:order];
    order.backgroundColor=[UIColor whiteColor];
    [order mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(headView).priorityHigh();
        make.top.equalTo(logBack.mas_bottom).with.offset(10).priorityHigh();
        make.height.offset(120).priorityHigh();
    }];
    
    UILabel *Myorder=[[UILabel alloc] init];
    Myorder.text=Localized(@"我的订单");
    Myorder.font=[UIFont systemFontOfSize:15];
    [order addSubview:Myorder];
    [Myorder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(order).with.offset(15);
        make.top.equalTo(order);
        make.height.offset(44);
    }];

    UIButton *allOrder=[UIButton buttonWithType:UIButtonTypeCustom];
    [order addSubview:allOrder];
    allOrder.titleLabel.font=[UIFont systemFontOfSize:14];
    [allOrder setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [allOrder setTitle:Localized(@"全部订单>") forState:UIControlStateNormal];
    allOrder.tag=249;
    [allOrder addTarget:self action:@selector(orderList:) forControlEvents:UIControlEventTouchUpInside];
    [allOrder setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [allOrder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(Myorder);
        make.right.equalTo(order.mas_right).with.offset(-15);
    }];
    [allOrder layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
    
    
    UIView *line=[[UIView alloc] init];
    [order addSubview:line];
    line.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(order).with.offset(15);
        make.right.equalTo(order).with.offset(-15);
        make.top.equalTo(order).with.offset(43);
        make.height.offset(1);
    }];
    
    //订单栏按钮文字图片
    NSArray *orderArr=@[Localized(@"待付款"),Localized(@"待发货"),Localized(@"待收货"),Localized(@"待评价"),Localized(@"售后/退款")];
    NSArray *image=@[@"待付款",@"待发货",@"待收货",@"待评价",@"售后退款"];
    for (int i=0; i<orderArr.count; i++) {
        UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setTitle:orderArr[i] forState:UIControlStateNormal];
        but.titleLabel.font=[UIFont systemFontOfSize:13];
        [but setImage:[UIImage imageNamed:image[i]] forState:UIControlStateNormal];
    
        [order addSubview:but];
        [but mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line);
            make.bottom.equalTo(order);
            make.width.offset(SCREEN_WIDTH/5);
            make.left.equalTo(order).with.offset((SCREEN_WIDTH/5)*i);
        }];
        [but layoutIfNeeded];
        but.tag=250+i;
        but.titleLabel.numberOfLines = 2;
        but.titleLabel.textAlignment = NSTextAlignmentCenter;
        [but addTarget:self action:@selector(orderList:) forControlEvents:UIControlEventTouchUpInside];
        but.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [but layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];

    }

    
    
    
    UIView *menu=[[UIView alloc]init];
    headView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [headView addSubview:menu];
    menu.backgroundColor=[UIColor whiteColor];
    [menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(order.mas_bottom).with.offset(10).priorityHigh();
        make.left.right.equalTo(headView).priorityHigh();
        make.height.offset(270).priorityHigh();
        make.bottom.equalTo(headView.mas_bottom).with.offset(-10).priorityHigh();
    }];
    
//    NSArray *menuArr=@[@"浏览记录",@"收货地址",@"购物车",@"积分商城",@"银行卡",@"收藏商品",@"收藏店铺",@"优惠券"];
    //菜单栏按钮文字图片
    NSArray *imageArr=@[@"收货地址",@"积分商城",@"我的收藏",@"短消息",@"优惠券",@"我的分享",@"信用管理",@"资金明细",@"我的社交"];
    NSArray *menuArr=@[Localized(@"收货地址"),Localized(@"积分商城"),Localized(@"我的收藏"),Localized(@"短消息"),Localized(@"优惠券"),Localized(@"我的分享"),Localized(@"信用管理"),Localized(@"资金明细"),Localized(@"我的社交")];
    for (int i=0; i<menuArr.count; i++) {
        
        UIView *back=[[UIView alloc] init];
        [menu addSubview:back];
        ViewBorderRadius(back, 0, 0.5, [UIColor groupTableViewBackgroundColor]);
        [back mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(menu).with.offset(i/3*90);
            make.left.equalTo(menu).with.offset(i%3*SCREEN_WIDTH/3);
            make.width.offset(SCREEN_WIDTH/3);
            make.height.offset(90);
        }];
        
        UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setTitle:menuArr[i] forState:UIControlStateNormal];
        but.titleLabel.font=[UIFont systemFontOfSize:13];
        [but setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [back addSubview:but];
        [but mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(back);
        }];
        [but layoutIfNeeded];
        but.tag=500+i;
        but.titleLabel.numberOfLines = 2;
        but.titleLabel.textAlignment = NSTextAlignmentCenter;
        [but addTarget:self action:@selector(butAction:) forControlEvents:UIControlEventTouchUpInside];
        but.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [but layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];
    }
    
    //第一次进入从缓存拿数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data=[defaults objectForKey:@"userInfo"];
    self.model=[NSKeyedUnarchiver unarchiveObjectWithData:data];
    [head sd_setImageWithURL: [NSURL URLWithString:[NSString stringWithFormat:@"%@union/images/%@",IMGURL,self.model.member_image]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
    integral.text=[NSString stringWithFormat:@"积分  :  %@",self.model.member_point];
    name.text=self.model.member_id;
    
    CGFloat height = [headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headView.bounds;
    frame.size.height = height;
    headView.frame = frame;
    [self.myTableview setTableHeaderView:headView];
}
-(void)orderList:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:Localized(@"售后/退款")]) {
        [self refund];
    }else{
        self.hidesBottomBarWhenPushed=YES;
        OrderListVC *order=[[OrderListVC alloc]init];
        order.type=sender.tag-250;
        [self.navigationController pushViewController:order animated:YES];
        self.hidesBottomBarWhenPushed=NO;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;;
    }
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        //        _myTableview.emptyDataSetSource=self;
        //        _myTableview.emptyDataSetDelegate=self;
        _myTableview.scrollEnabled = YES;
    }
    return _myTableview;
}

@end
